const router = require('koa-router')();
const fileUtils = require('../util/fileUtils');
const fileService = require('../service/fileService');

router.prefix('/api/file');

/**
 * @api {post} /api/file/upload 上传图片
 * @apiGroup file
 * @apiName upload
 *
 * @apiSuccess {int} code 返回状态码（1：上传成功，3：服务器出错）
 * @apiSuccess {String} msg 返回状态码对应的信息
 * @apiSuccess {json} data 上传成功时返回的图片名{file_path:'xxx'}
 */

router.post('/upload', fileUtils.single('file'), async (ctx) => {
    try {
        ctx.body = {code: 1, msg: '上传成功！', data: {file_path: '/' + ctx.req.file.filename}};
    } catch (e) {
        let data = {code: 3, msg: e.message};
        ctx.body = data;
    }
});

/**
 * @api {post} /api/file/delete  删除文件（逻辑删除）
 * @apiGroup file
 * @apiName delete
 * @apiParam {String} file_id  文件id
 */
router.post('/delete', async (ctx) => {
    try {
        let data = ctx.request.body;
        if (!data.file_id) {
            ctx.body = {code: 4, msg: '缺少参数！'};
            return;
        }
        let result = await fileService.deleteFile(data);
        ctx.body = result;
    } catch (e) {
        if (!e.message) {
            logger.writeErr(e.message);
            ctx.body = {code: 3, msg: e.message}
        } else {
            ctx.body = e;
        }
    }
});

/**
 * @api {post} /api/file/uploadMain 上传主图
 * @apiGroup file
 * @apiName uploadMain
 *
 * @apiSuccess {int} code 返回状态码（1：上传成功，2：上传失败，3：服务器出错）
 * @apiSuccess {String} msg 返回状态码对应的信息
 * @apiSuccess {json} data 上传成功时返回的图片名{file_path:'xxx'}
 *
 */

router.post('/uploadMain', fileUtils.single('file'), async (ctx) => {
    try {
        const path = ctx.req.file.filename;
        if (!path) {
            let data = {code: 4, msg: '参数不全！'};
            ctx.body = data;
            return;
        }
        let result;
        result = await fileService.handleUploadMain('/' + path);
        if (result.code === 1) {
            ctx.body = {code: 1, msg: '上传成功！', data: {file_path: '/' + path}};
        } else {
            result.msg = '上传失败！';
            ctx.body = result;
        }
    } catch (e) {
        let data = {code: 3, msg: e.message};
        ctx.body = data;
    }
});

module.exports = router;